﻿using Api1.Helper;
using Api1.Service;
using Api1.Util;
using ArcsoftFaceTest;
using Camera;
using Newtonsoft.Json;
using ocmctr;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using WebKit;

namespace Api1
{
    [System.Runtime.InteropServices.ComVisible(true)]
    ///IE  和 CHROME
    public partial class zwForm : Form
    {
        //是否完成密钥配置  1是 0 否
        public static String auto_key = OperateIniFile.ReadIniData("Config", "auto_key", "0");
        //主机api
        public static String host = "http://" + OperateIniFile.ReadIniData("Config", "host", "127.0.0.1") + "/";
        public static String server = host + "admin/main/login/type/auto";
        //IE OR CHROME
        public static String Browser = OperateIniFile.ReadIniData("Config", "Browser", "IE");
        //模板是否黑白照片  0不是 1是
        public static String IsBlackImage = OperateIniFile.ReadIniData("Config", "IsBlackImage", "0");
        //锁体版本号  0旧的锁（不能上传柜号），  1新的锁（能上传柜号）
        public static String lock_version = OperateIniFile.ReadIniData("Config", "LockVersion", "0");


        //是否为从机（如果是从机则上传图片到主机）
        public static String is_slave = OperateIniFile.ReadIniData("Config", "is_slave", "0");
        //人脸特征码
        public static String[] face = new String[3] { "", "", "" };
        //人脸模板url地址
        public static String[] faceUrl = new String[3] { "", "", "" };

        public static AmFaceVerify amface = null;
        //IE览器内核
        public static WebBrowser webBrowser;
        //CHROME 浏览器内核
        public static WebKitBrowser webKitBrowser;

        //照相机实例
        public static CameraForm camera_instance = null;
        public static String finger_path = "C:/wamp/www/anke/data/finger/";


        //实现窗口拖动
        [DllImport("user32.dll")]
        public static extern bool ReleaseCapture();
        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
        public const int WM_SYSCOMMAND = 0x0112;
        public const int SC_MOVE = 0xF010;
        public const int HTCAPTION = 0x0002;
        /// <summary>
        /// 读卡程序
        /// </summary>
        public static UmfCtr umf = null;
        //指纹处理
        public static FingerCtr finger = new ocmctr.FingerCtr();
        public static PictureBox fgPic = new PictureBox();
        byte[] fingerTemp = new byte[512];

        int sysInt = 0;
        bool umflink = false;
        bool fingerlink = false;
        public delegate void updateTipHandler(string msg);
        public delegate void CallBack(int state);


        public static Boolean autorun = false;
        /// <summary>
        /// 1 强制停止
        /// 0 否
        /// </summary>
        public static int _lock = 0;
        private static object locker = new object();
        /// <summary>
        /// 中未智联发出去的手环 设置成0  (装载配置密码)
        /// 中未智联发出去的手环 设置成1  (装载默认密码和配置密码)
        /// </summary>
        public string autoSetKey = ConfigurationManager.AppSettings["autoSetKey"].ToString();

        /// <summary>
        ///
        /// </summary>
        int checkTime = 10000;
        bool checkFlag = true;
        /// <summary>
        /// 设备重新
        /// </summary>
        private void devCheck()
        {
            while (checkFlag)
            {
                if (!autorun & _lock == 0)
                {
                    Reconncet();
                }
                Thread.Sleep(checkTime);
            }
        }

        public zwForm()
        {
            if (ParamLoad())
            {
                InitializeComponent();
                UILoad();
                UmfCtr.lockVersion = Convert.ToInt16(lock_version);
                Reconncet();
                new Thread(new ThreadStart(devCheck)).Start();
            }
        }

        void UILoad()
        {
            this.StartPosition = FormStartPosition.CenterScreen;
            this.FormClosing += zwForm_FormClosing;
            this.Load += zwForm_Load;
            if (Browser.Equals("IE"))
            {
                label3.Text = "重庆一厘米科技(V2-IE-v2)";
            }
            else if (Browser.Equals("CHROME")) {
                label3.Text = "重庆一厘米科技(V2-CHROME-v2)";
            }
        }

        private void zwForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            closeDev();
        }

        /// <summary>
        /// 是否启动程序
        /// </summary>
        /// <returns></returns>
        public Boolean ParamLoad()
        {
            try
            {
                umf = new ocmctr.UmfCtr();
                if (!autoSetKey.Equals("1"))
                    umf.setAutoType(false);
                else
                    umf.setAutoType(true);
            }
            catch (Exception)
            {
                Process.Start(Application.StartupPath + "\\中未密钥.exe");
                OperateIniFile.WriteIniData("Config", "auto_key", "0");
                return false;
            }
            return true;
        }

        public string WriteAuth(string auth)
        {
            Before_Write();
            String result = umf.WriteAuth(auth);
            After_Write();
            return result;
        }
        public string ReadAuth()
        {
            Before_Write();
            String res = umf.ReadAuth();
            After_Write();
            return res;
        }
        /// <summary>
        /// 查询柜号
        /// </summary>
        /// <returns></returns>
        public string ReadCupNo()
        {
            Before_Write();
            String res = umf.ReadCupNo();
            After_Write();
            return res;
        }
       
        void zwForm_DoubleClick(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Maximized)
            {
                this.WindowState = FormWindowState.Normal;
            }
            else
            {
                this.FormBorderStyle = FormBorderStyle.None;
                this.MaximumSize = new Size(Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height);
                this.WindowState = FormWindowState.Maximized;
            }
            if (Browser.Equals("IE"))
            {
                webBrowser.Refresh();
            }
            else if (Browser.Equals("CHROME")) {
                webKitBrowser.Reload();
            }
        }
        public Boolean IsAutoRun()
        {
            return autorun;
        }
        void zwForm_Load(object sender, System.EventArgs e)
        {
            if (Browser.Equals("IE"))
            {
                webBrowser = new WebBrowser
                {
                    Dock = DockStyle.Fill
                };
                webBrowser.ObjectForScripting = this;
                panelbox.Controls.Add(webBrowser);
            }
            else if (Browser.Equals("CHROME"))
            {
                webKitBrowser = new WebKitBrowser
                {
                    Dock = DockStyle.Fill,
                    AllowDownloads = true,
                    AllowNavigation = true,
                    UseJavaScript = true,
                    AllowNewWindows = true,
                    AllowCookies = true,
                    EnableHTTPPipelining = true,
                    PrivateBrowsing = false,
                };

                panelbox.Controls.Add(webKitBrowser);
                webKitBrowser.DocumentCompleted += WebKitBrowser_DocumentCompleted;
            }
            init();
        }

        void WebKitBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {
            webKitBrowser.GetScriptManager.ScriptObject = new JsInterface(this);
        }
        private void init()
        {   
            if (Browser.Equals("IE"))
            {
                webBrowser.Url = new System.Uri(server);
            }
            else if (Browser.Equals("CHROME"))
            {
                webKitBrowser.Url = new System.Uri(server);
            }
            checkDevThread();

        }

        /// <summary>
        /// 设置员工能否开柜
        /// </summary>
        /// <param name="value">1能，0不能</param>
        /// <returns></returns>
        public string StaffCardSet(string value)
        {
            Before_Write();
            String result = umf.staffCardSet(value);
            After_Write();
            return result;

        }

        /// <summary>
        /// 读查询卡
        /// </summary>
        /// <returns></returns>
        public string ReadNoNumber()
        {
            Before_Write();
            String res = umf.ReadNoNumber();
            After_Write();
            return res;

        }

        int UmfTryNum = 10;
        private void checkDevThread()
        {
            ThreadPool.QueueUserWorkItem(checkUmf, "");
            ThreadPool.QueueUserWorkItem(checkFinger, "");
        }
        private void checkUmf(object state)
        {
            bool res = false;
            while (!umflink && UmfTryNum-- > 0)
            {
                try
                {
                    res = umf.openDev(0, 0, 0);
                }
                catch (Exception e)
                {
                    //Console.WriteLine(e.StackTrace);
                }
                if (res)
                {
                    umflink = true;
                    StartAutoRead();
                }
                Thread.Sleep(1000);
            }
        }


        public string ClearCard()
        {
            Before_Write();
            String res = umf.ClearCard();
            After_Write();
            return res;
        }
        /// <summary>
        /// true 租用柜
        /// false 普通柜
        /// </summary>
        /// <returns></returns>
        public string ClearCupNo(String flag) {
            Before_Write();
            String res = umf.ClearCupNo(flag);
            After_Write();
            return res.ToString();
        }


        private void checkFinger(object state)
        {
            int ret = -1;
            while (!fingerlink)
            {
                try
                {
                    ret = finger.openDev();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.StackTrace);
                }
                if (ret == 0)
                {
                    fingerlink = true;
                }
                Thread.Sleep(1000);
            }
        }

        private void btnDevReset_Click(object sender, EventArgs e)
        {
            Reconncet();
        }
        public static void StartAutoRead()
        {
            lock (locker) {
                if (autorun) return;
                autorun = true;
                new Thread(new ThreadStart(readloop)).Start();
            }

        }
        public static void StopAutoRead()
        {
            lock (locker) {
                autorun = false;
            }

        }
        public void JsStartAutoRead()
        {
            lock (locker)
            {
                Thread.Sleep(100);
                if (autorun) return;
                autorun = true;
                new Thread(new ThreadStart(readloop)).Start();
            }

        }
        public void JsStopAutoRead()
        {
            lock (locker)
            {
                Thread.Sleep(100);
                autorun = false;
            }
        }
        /// <summary>
        /// 是否自动读卡
        /// </summary>
        /// <returns></returns>
        public bool IsAutoRead()
        {
            return autorun;
        }
        public static void readloop()
        {
            Thread.Sleep(200);
            string _cardno = "";
            string res = "";
            while (autorun)
            {
                res = umf.getCardNoLoop(ref _cardno);
                if (res.Equals("0") && !_cardno.Equals(""))
                {
                    while (_cardno.Length < 10) _cardno = "0" + _cardno;
                    SendKeys.SendWait(_cardno);
                }
                _cardno = "";
            }
        }


        public static void closeDev()
        {
            try {
                StopAutoRead();
                umf.closeDev();
            } catch (Exception e) {

            }

        }
        public string Reconncet()
        {
            closeDev();
            string res = "";
            if (umf.openDev(0, 0, 0))
            {
                umflink = true;
                res = "0";
                StartAutoRead();
            }
            else
            {
                if (umf.openDev(0, 0, 0))
                {
                    umflink = true;
                    res = "0";
                    StartAutoRead();
                }
                else res = "1";
            }
            return res;
        }

        /// <summary>
        /// 制卡
        /// </summary>
        public string MakeCard()
        {
            Before_Write();
            String res = umf.MakeCard();
            After_Write();
            return res.ToString();
        }

        public string CardError(int type)
        {
            switch (type)
            {
                case -1:
                    return "寻卡错误";
                case -2:
                    return "校验失败";
                case -3:
                    return "制卡失败";
                case -4:
                    return "读卡错误";
                case -5:
                    return "加密错误";
                default:
                    return "未知错误";
            }
        }
        /// <summary>
        /// 清理卡  还原成白卡
        /// </summary>
        /// <returns></returns>
        public string RestCard()
        {
            Before_Write();
            String res = umf.resetCard();
            After_Write();
            return res;
        }
        /// <summary>
        /// 设置不能存柜
        /// </summary>
        /// <returns></returns>

        public string MakeNoCupCard()
        {
            Before_Write();
            String res = umf.MakeNoCupCard();
            After_Write();
            return res;
        }


        /// <summary>
        /// 制匹配卡 
        /// @param 10位的10进制 卡号
        /// </summary>
        public string QueryCard(string cardno)
        {
            Before_Write();
            String res = umf.QueryCard(cardno);
            After_Write();
            return res.ToString();
        }
        /// <summary>
        /// 查询机
        /// </summary>
        /// <returns></returns>
        public string StateCard()
        {
            Before_Write();
            String res = umf.StateCard();
            After_Write();
            return res.ToString();
        }

        bool IsAuto()
        {
            return sysInt == 1;
        }
        public string GetError(string err)
        {
            switch (err)
            {
                case "-1": return "寻卡失败";
                case "-2": return "校验失败";
                case "-3": return "制卡失败";
                case "-4": return "读卡失败";
                case "-5": return "加密失败";
                case "-6": return "清柜失败";
                case "-11": return "功能卡，不能制卡";
                case "-12": return "不是查询卡";
                case "-13": return "参数错误，应传入8位16进制";
                case "-15": return "指纹录取失败";
                case "-16": return "未绑定租柜，无需清租柜";
                default: return "未知错误";
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="num">柜子编号</param>
        /// <param name="gender">0女 1男 2C，3D，4E，5F，6G</param>
        /// <returns></returns>
        public string EditNoCard(string num, string gender)
        {
            Before_Write();
            String res = umf.EditNoCard(num, gender);
            After_Write();
            return res;
        }

        /// <summary>
        /// 录指纹
        /// </summary>
        public void SignFinger1()
        {
            byte[] ImgData = new byte[256 * 288];
            int ret = 0;
            finger.connect_usb();
            if (fingerlink)
            {
                ret = finger.connect_usb();
                if (ret != 0)
                { goto ENDERR; }
                if (finger.getchar(1, 1000, ref ImgData) != 1)
                { goto ENDERR; }
                else
                {
                    string _fingerImgPath = @finger_path + "finger1" + DateTime.Now.Ticks + ".bmp";
                    ret = finger.downImg(ImgData, _fingerImgPath);
                    if (ret == 0)
                    {
                        string base64 = ByteHelper.GetBase64(_fingerImgPath);
                        // webBrowser.Document.InvokeScript("SignFinger1CallBack", new object[] { "data:image/png;base64," + base64 });
                        if (Browser.Equals("IE"))
                        {
                            webBrowser.Document.InvokeScript("SignFinger1CallBack", new object[] { "data:image/png;base64," + base64 });
                        }
                        else if (Browser.Equals("CHROME"))
                        {
                            webKitBrowser.GetScriptManager.CallFunction("SignFinger1CallBack", new object[] { "data:image/png;base64," + base64 });
                        }
                    }
                }
                ENDERR:
                finger.connect_close();
                return;
            }
        }
        /// <summary>
        /// 第二次录制指纹
        /// </summary>
        public void SignFinger2()
        {
            byte[] ImgData = new byte[256 * 288];
            int tempLen = 0;
            int ret = 0;
            byte[] temp = new byte[512];
            if (fingerlink)
            {
                ret = finger.connect_usb();
                if (ret != 0)
                { goto ENDERR; }
                if (finger.getchar(2, 1000, ref ImgData) != 1)
                { goto ENDERR; }
                else
                {
                    string _fingerImgPath = finger_path + "finger2" + DateTime.Now.Ticks + ".bmp";
                    ret = finger.downImg(ImgData, _fingerImgPath);
                    if (ret == 0)
                    {
                        string base64 = ByteHelper.GetBase64(_fingerImgPath);
                        // webBrowser.Document.InvokeScript("SignFinger2CallBack", new object[] { "data:image/png;base64," + base64 });
                        if (Browser.Equals("IE"))
                        {
                            webBrowser.Document.InvokeScript("SignFinger2CallBack", new object[] { "data:image/png;base64," + base64 });
                        }
                        else if (Browser.Equals("CHROME"))
                        {
                            webKitBrowser.GetScriptManager.CallFunction("SignFinger2CallBack", new object[] { "data:image/png;base64," + base64 });
                        }

                    }
                    ret = finger.upChar(ref temp, ref tempLen);
                    if (ret == 0)
                    {
                        string fingerdata = BitConverter.ToString(temp).Replace("-", "");
                        // webBrowser.Document.InvokeScript("FingerDataCallBack", new object[] { fingerdata });
                        if (Browser.Equals("IE"))
                        {
                            webBrowser.Document.InvokeScript("FingerDataCallBack", new object[] { fingerdata });
                        }
                        else if (Browser.Equals("CHROME"))
                        {
                            webKitBrowser.GetScriptManager.CallFunction("FingerDataCallBack", new object[] { fingerdata });
                        }

                        //录取成功
                    }
                    else {
                        // webBrowser.Document.InvokeScript("FingerDataCallBack", new object[] { "-15", "" });
                        if (Browser.Equals("IE"))
                        {
                            webBrowser.Document.InvokeScript("FingerDataCallBack", new object[] { "-15", "" });
                        }
                        else if (Browser.Equals("CHROME"))
                        {
                            webKitBrowser.GetScriptManager.CallFunction("FingerDataCallBack", new object[] { "-15", "" });
                        }
                    }
                    finger.connect_close();
                }
                ENDERR:
                finger.connect_close();
                return;
            }
        }

        private void erollfp1(object state)
        {
            byte[] temp = new byte[512];
            int ret = 0;
            byte[] ImgData = new byte[256 * 288];
            finger.closeDev();
            ret = finger.connect_usb();
            if (ret != 0)
            { goto ENDERR; }
            //获取指纹图像 
            if (finger.getchar(1, 2000, fgPic.Handle, ref ImgData) != 1)
            { goto ENDERR; }

            ENDERR:
            finger.connect_close();
            return;
        }
        private void btnClose_Click(object sender, EventArgs e)
        {
            try
            {
                this.Dispose();
                Application.Exit();
                Application.ExitThread();
                System.Environment.Exit(0);
                
            }
            catch (Exception)
            {

                throw;
            }
            
        }

        const int Guying_HTLEFT = 10;
        const int Guying_HTRIGHT = 11;
        const int Guying_HTTOP = 12;
        const int Guying_HTTOPLEFT = 13;
        const int Guying_HTTOPRIGHT = 14;
        const int Guying_HTBOTTOM = 15;
        const int Guying_HTBOTTOMLEFT = 0x10;
        const int Guying_HTBOTTOMRIGHT = 17;



        public string GetMemberInfo(String card_no)
        {
            Dictionary<String, Object> obj = OcmApiService.GetInstance().GetContractInfo(card_no);
            return JsonConvert.SerializeObject(obj);
        }
        /// <summary>
        /// 人脸比对
        /// </summary>
        /// <returns></returns>
        public static float TestFaceMath(byte[] s, byte[] s1) {
            if (amface == null)
            {
                amface = new AmFaceVerify();
                amface.AFD_Init();
            }
            return amface.matchFace(s, s1);
        }
        public static byte[] TestFaceDetect(String path)
        {
            if (amface == null)
            {
                amface = new AmFaceVerify();
                amface.AFD_Init();
            }
            return amface.detectFace(path);
        }
        /// <summary>
        /// 获取特征码
        /// </summary>
        /// <param name="pathnames"></param>
        /// <returns></returns>
        public static string[] GetDetect(string pathnames)
        {
            if (amface == null)
            {
                amface = new AmFaceVerify();
                amface.AFD_Init();
            }

            string[] names = pathnames.Split(',');
            string[] detects = new string[names.Length];
            for (int i = 0; i < names.Length; ++i)
            {
                if (File.Exists(names[i]))
                {
                    byte[] res = amface.detectFace(names[i]);
                    if (res != null) detects[i] = ByteHelper.ToHexString(res);
                }
            }
            return detects;
        }

        private void toolBar_Paint(object sender, PaintEventArgs e)
        {

        }


        private void win_moves(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                ReleaseCapture();
                SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
            }
        }

        private void win_min(object sender, MouseEventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        private void btnOption_Click(object sender, EventArgs e)
        {

            if (MainTab.instance == null)
            {
                MainTab.instance = new MainTab();
                MainTab.instance.Show();
            }
            else {
                MainTab.instance.Activate();
            }

        }
        /// <summary>
        /// 打开照相机
        /// </summary>
        public void OpenCamare()
        {
            try
            {
                if (camera_instance == null)
                {
                    camera_instance = new CameraForm();
                    camera_instance.Show();
                }
                camera_instance.Activate();
                camera_instance.BringToFront();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        //获取人脸模板code
        public String GetFaceCode() {
            String result = String.Join(",", face);
            return result;
        }
        //获取人脸模板地址
        public String GetFaceUrl()
        {
            return String.Join(",", faceUrl);
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        public static void upload_image(string path, string fileName)
        {
            if (is_slave.Equals("1"))
            {//如果是丛机才 上传图片到主机
                String data = ByteHelper.GetBase64(@path);
                try
                {
                    string url = host + "api/UploadFace/upload";
                    WebClient webClient = new WebClient();
                    webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                    webClient.UploadData(url, "POST", Encoding.UTF8.GetBytes("filename=" + fileName + "&files=" + data));

                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString());
                }
            }
        }
        /// <summary>
        /// 下载excel
        /// </summary>
        public void Down_Excel(String url) {
            System.Diagnostics.Process.Start(host + url);
        }
        /// <summary>
        /// 写卡前的操作
        /// </summary>
        private static void Before_Write() {
            if (autorun) {
                StopAutoRead();
            }
            Thread.Sleep(100);
        }
        /// <summary>
        /// 写完后开启自动读卡
        /// </summary>
        private static void After_Write() {
            if (_lock == 0) {
                if (!autorun)
                {
                    StartAutoRead();
                }
            }
            Thread.Sleep(100);
        }


        /// <summary>
        /// 是否绑定了租柜
        /// </summary>
        /// <returns>-7已绑定  0未绑定</returns>
        public string IsRent()
        {
            Before_Write();
            String flag = umf.isRentCup().ToString();
            After_Write();
            return flag;
        }

        /// <summary>
        /// 读取租柜 临时柜
        /// </summary>
        /// <returns>{cupno:'租用 E 999',rentcupno:'租用 男 155',record:'租用 E 999,租用 男 155,租用 男 4',usrent:'1'}</returns>
        public string ReadSmartCupNo()
        {
            Before_Write();
            String res = umf.ReadSmartCupNo();
            After_Write();
            return res;
        }

        /// <summary>
        /// 设置水泵
        /// </summary>
        /// <param name="type">0 不能充值 1自动充值  ,2：无限次， 3：每次扣1 </param>
        /// <param name="count">充值次数</param>
        /// <param name="munute">充值时间</param>
        /// <returns></returns>
        public string SetWaterPump(int type, int count, int munute) {
            Before_Write();
            String result = umf.setWaterPump(type, count, munute);
            After_Write();
            return result;
        }

        public static UmfCtr _test_get_umf() {
            return umf;
        }
        /// <summary>
        /// 测试查询存储记录
        /// </summary>
        /// <returns></returns>
        public static Boolean _test_focus_stop() {
            StopAutoRead();
            _lock = 1;
            return autorun;
        }
        public static Boolean _test_focus_start() {
            StartAutoRead();
            _lock = 0;
            return autorun;
        }
        private void label3_Click(object sender, EventArgs e)
        {
            //for (int k = 1; k < 14; k++) {
            //    ImageConver.GrayImage(new Bitmap(Image.FromFile(@"C:/("+k+").jpg")),1).Save("C:/a("+k+").jpg");    
            //}

            //String str = "";
            //for (int i = 0; i < 14; i++)
            //{
            //    //str += "c:/(" + i + ").jpg," + "c:/a(" + i + ").jpg,";
            //    str +="c:/a(" + i + ").jpg,";
            //}
            // String str = "c:/1.jpeg";
            // string[] s=GetDetect(@str);
            //Console.WriteLine();
        }

        private void zwForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {

                this.Dispose();
                Application.Exit();
                Application.ExitThread();
                System.Environment.Exit(0);
            }
            catch (Exception)
            {

                throw;
            }
            
        
        }

    }

}
